package cn.wolfcode.web.controller;

import cn.wolfcode.common.constants.CommonConstants;
import cn.wolfcode.common.domain.UserInfo;
import cn.wolfcode.common.web.Result;
import cn.wolfcode.common.web.anno.RequireLogin;
import cn.wolfcode.domain.Condition;
import cn.wolfcode.domain.PostFormDto;
import cn.wolfcode.domain.UserLogin;
import cn.wolfcode.domain.UserResponse;
import cn.wolfcode.service.IUserService;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@Slf4j
@RequestMapping("/user")
public class LoginController {
    private final IUserService userService;

    public LoginController(IUserService userService) {
        this.userService = userService;
    }

    @PostMapping("/login")
    public Result<UserResponse> login(@RequestBody UserLogin userLogin,
                                      @RequestHeader(value = CommonConstants.REAL_IP, required = false) String ip,
                                      @RequestHeader(value = CommonConstants.TOKEN_NAME, required = false) String token) {
        /**
         * 获取用户IP,因为微服务的请求是网关转发过来的.
         * 所以request.getRemoteAddr()获取到的是网关的IP
         * 我们需要在网关中获取到真实IP,然后放入到请求头中。
         * 在微服务中通过获取请求头从而获取到真实的客户端IP
         */
        //进行登录，并将这个token返回给前台
        UserResponse userResponse = userService.login(userLogin.getPhone(), userLogin.getPassword(), ip, token);
        return Result.success(userResponse);
    }
    @RequireLogin
    @PostMapping("/conditionFindByPage")
    public Result<PageInfo<UserInfo>> conditionFindByPage(@RequestBody Condition condition,@RequestParam("page") Integer page,
                                                          @RequestParam("pageSize") Integer pageSize) {
        return Result.success(userService.conditionFindByPage(page, pageSize, condition));
    }
    @RequireLogin
    @PostMapping("/addUser")
    public Result<?> addUser(@RequestBody PostFormDto postFormDto) {
        userService.addUser(postFormDto);
        return Result.success();
    }
    @RequireLogin
    @PostMapping("/updateUser")
    public Result<?> updateUser(@RequestBody UserInfo userInfo) {
        userService.updateUser(userInfo);
        return Result.success();
    }
    @RequireLogin
    @PostMapping("/batchDeleteUser")
    public Result<?> batchDeleteUser(@RequestBody List<Long> ids) {
        userService.batchDeleteUser(ids);
        return Result.success();
    }

}
